import time
import json
from django.conf import settings
from django.db import connection
from django.utils import timezone


class UserBehaviorMiddleware:
    """
    中间件用于跟踪和记录用户行为
    """
    
    def __init__(self, get_response):
        self.get_response = get_response
        self.tracking_enabled = getattr(settings, 'BEHAVIOR_TRACKING', {}).get('ENABLED', False)
        self.exclude_paths = getattr(settings, 'BEHAVIOR_TRACKING', {}).get('EXCLUDE_PATHS', [])
        
    def __call__(self, request):
        # 获取开始时间
        start_time = time.time()
        
        # 处理请求
        response = self.get_response(request)
        
        # 计算请求处理时间
        processing_time = time.time() - start_time
        
        # 如果跟踪功能已启用且请求路径不在排除列表中
        if self.tracking_enabled and not any(request.path.startswith(path) for path in self.exclude_paths):
            self.track_user_behavior(request, response, processing_time)
            
        return response
    
    def track_user_behavior(self, request, response, processing_time):
        # 排除对跟踪API的请求
        if request.path.endswith('/track/'):
            return
        
        """记录用户行为数据"""
        # 确保请求成功 (状态码 2xx) 且用户已登录
        if 200 <= response.status_code < 300 and request.user.is_authenticated:
            # 获取用户ID (已认证用户)
            user_id = request.user.user_id
            
            # 获取会话ID
            session_id = request.session.session_key
            
            # 获取IP地址
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip_address = x_forwarded_for.split(',')[0]
            else:
                ip_address = request.META.get('REMOTE_ADDR')
                
            # 获取用户代理字符串
            user_agent = request.META.get('HTTP_USER_AGENT', '')
            
            # 获取引荐来源
            referer = request.META.get('HTTP_REFERER', '')
            
            # 确定行为类型和目标
            action_type = self.determine_behavior_type(request)
            object_id, object_type = self.determine_target(request)
            
            # 获取当前URL
            url = request.path
            
            # 获取搜索查询
            query = request.GET.get('q', '') if 'search' in request.path else None
            
            # 记录到数据库
            if hasattr(connection, 'ensure_connection'):
                connection.ensure_connection()
                
            try:
                with connection.cursor() as cursor:
                    cursor.execute("""
                        INSERT INTO tb_user_behavior 
                        (user_id, session_id, action_type, object_type, object_id, url, query, user_agent, ip_address, create_time)
                        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                    """, [
                        user_id,
                        session_id,
                        action_type,
                        object_type,
                        object_id,
                        url,
                        query,
                        user_agent[:255] if user_agent else None,
                        ip_address[:50] if ip_address else None,
                        timezone.now()
                    ])
            except Exception as e:
                # 生产环境中应记录日志而不是打印
                if settings.DEBUG:
                    print(f"行为跟踪记录失败: {e}")
    
    def determine_behavior_type(self, request):
        """根据请求确定行为类型"""
        if request.method == 'GET':
            if 'blindbox' in request.path:
                return 'view_box'
            elif 'market' in request.path:
                return 'view_market'
            elif 'order' in request.path:
                return 'view_order'
            else:
                return 'page_view'
        elif request.method == 'POST':
            if 'shopping/add' in request.path:
                return 'add_to_cart'
            elif 'shopping/checkout' in request.path:
                return 'checkout'
            elif 'blindbox/draw' in request.path:
                return 'draw_box'
            elif 'accounts/login' in request.path:
                return 'login'
            elif 'accounts/register' in request.path:
                return 'register'
            else:
                return 'form_submit'
        return 'other'
    
    def determine_target(self, request):
        """确定目标ID和类型"""
        # 盲盒详情
        if 'blindbox/detail' in request.path:
            box_id = request.path.split('/')[-1]
            try:
                return int(box_id), 'box'
            except (ValueError, IndexError):
                pass
        
        # 超市详情
        elif 'market/detail' in request.path:
            market_id = request.path.split('/')[-1]
            try:
                return int(market_id), 'market'
            except (ValueError, IndexError):
                pass
                
        # 订单详情
        elif 'order/detail' in request.path:
            order_id = request.path.split('/')[-1]
            try:
                return int(order_id), 'order'
            except (ValueError, IndexError):
                pass
                
        # 默认返回空值
        return None, None 